'use client'

import { Fragment, useState } from 'react'
import { Dialog, Transition } from '@headlessui/react'
import { useForm } from 'react-hook-form'
import { FormInput, FormTextarea } from '@/components/ui/form'
import { updateExpense } from '@/actions/expense'
import { SerializedFinanceRecord } from '@/types'

interface EditExpenseDialogProps {
  record: SerializedFinanceRecord
  open: boolean
  onClose: () => void
}

interface ExpenseFormData {
  amount: string
  description: string
}

export function EditExpenseDialog({ record, open, onClose }: EditExpenseDialogProps) {
  const [submitting, setSubmitting] = useState(false)
  const { register, handleSubmit, formState: { errors } } = useForm<ExpenseFormData>({
    defaultValues: {
      amount: record.amount,
      description: record.description
    }
  })

  const onSubmit = async (data: ExpenseFormData) => {
    try {
      setSubmitting(true)
      const result = await updateExpense(record.id, data)
      if (result.success) {
        onClose()
      } else {
        alert(result.error)
      }
    } catch (error) {
      console.error('更新支出记录失败:', error)
      alert('更新支出记录失败')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <Transition show={open} as={Fragment}>
      <Dialog onClose={onClose} className="relative z-50">
        <Transition.Child
          as={Fragment}
          enter="ease-out duration-300"
          enterFrom="opacity-0"
          enterTo="opacity-100"
          leave="ease-in duration-200"
          leaveFrom="opacity-100"
          leaveTo="opacity-0"
        >
          <div className="fixed inset-0 bg-black/30" />
        </Transition.Child>

        <div className="fixed inset-0 overflow-y-auto">
          <div className="flex min-h-full items-center justify-center p-4">
            <Transition.Child
              as={Fragment}
              enter="ease-out duration-300"
              enterFrom="opacity-0 scale-95"
              enterTo="opacity-100 scale-100"
              leave="ease-in duration-200"
              leaveFrom="opacity-100 scale-100"
              leaveTo="opacity-0 scale-95"
            >
              <Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-lg bg-white shadow-xl transition-all">
                <div className="border-b border-gray-200 bg-white px-6 py-4">
                  <Dialog.Title as="h3" className="text-lg font-medium text-gray-900">
                    编辑支出
                  </Dialog.Title>
                </div>

                <form onSubmit={handleSubmit(onSubmit)}>
                  <div className="bg-white px-6 py-6 space-y-6">
                    <FormInput
                      label="支出金额"
                      type="number"
                      step="0.01"
                      {...register('amount', { 
                        required: '请输入支出金额',
                        min: { value: 0.01, message: '金额必须大于0' }
                      })}
                      error={errors.amount?.message}
                    />
                    <FormTextarea
                      label="支出说明"
                      {...register('description', { required: '请输入支出说明' })}
                      error={errors.description?.message}
                    />
                  </div>

                  <div className="border-t border-gray-200 bg-gray-50 px-6 py-4 flex justify-end gap-4">
                    <button
                      type="button"
                      onClick={onClose}
                      className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
                    >
                      取消
                    </button>
                    <button
                      type="submit"
                      disabled={submitting}
                      className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 disabled:opacity-50"
                    >
                      {submitting ? '提交中...' : '保存'}
                    </button>
                  </div>
                </form>
              </Dialog.Panel>
            </Transition.Child>
          </div>
        </div>
      </Dialog>
    </Transition>
  )
} 